<?php

namespace app\admin\controller\manage;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\HttpResponseException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Response;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Checkpoint extends Backend
{

    /**
     * Checkpoint模型对象
     * @var \app\admin\model\manage\Checkpoint
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\manage\Checkpoint;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage

            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','checkpoint','position_id','position','pointpic','qrcode','status','is_pic','create_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
//                    echo '<pre />';
//             var_dump($params);
//             echo Db::getLastSql();die;
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['create_time'] = date('Y-m-d H:i:s');
        $params = $this->preExcludeFields($params);
        $category = Db::name('wanlshop_category')->field('id,name')->where(array('id'=>$params['position_id']))->find();
        $params['position'] = $category['name'];
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $insid=$this->model->getLastInsID();


            //创建二维码
            $http_type=((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']=='https')) ? 'https://' : 'http://';
            $host = $http_type.$_SERVER['HTTP_HOST'];
            $text=$host.'/index.php/api/manage/index/do_check?point_id='.$insid;
            $lable=$params['checkpoint'];
            $qrcode=$this->build($text,$lable);
            $this->model->where(array('id'=>$insid))->update(array('qrcode'=>$qrcode));
//             echo '<pre />';
//             var_dump($qrcode);
//             echo Db::getLastSql();die;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $category = Db::name('wanlshop_category')->field('name')->where(array('id'=>$params['position']))->find();
        $params['position']=$category['name'];
        $params['update_time'] = date('Y-m-d H:i:s');
//                    echo '<pre />';
//             var_dump($params);
//             echo Db::getLastSql();die;
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            $insid=$ids;


            //创建二维码
            $http_type=((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']=='https')) ? 'https://' : 'http://';
            $host = $http_type.$_SERVER['HTTP_HOST'];
            $text=$host.'/index.php/api/manage/index/do_check?point_id='.$insid;
            $lable=$params['checkpoint'];
            $qrcode=$this->build($text,$lable);
            $this->model->where(array('id'=>$insid))->update(array('qrcode'=>$qrcode));

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function category(){
        $where['status'] = 'normal';
        $keyValue = $this->request->request('keyValue');
        if($keyValue){
            $id = $this->request->request('position_id');
            if($id){
                $where['id'] = $id;
            }
        }


//        echo '<pre />';
//             var_dump($list);
//             echo Db::getLastSql();die;
        $category = Db::name('wanlshop_category')->field('id,name')->where($where)->select();
        return json(['list' => $category, 'total' => count($category)]);
    }
    public function searchcategory(){
        $category = Db::name('wanlshop_category')->field('id,name')->where(array('status'=>'normal'))->select();
        return json($category);
    }
// 生成二维码
    public function build($text,$lable)
    {
        $config = get_addon_config('qrcode');

        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

//        $params['text'] = $this->request->get('text', $config['text'], 'trim');
//        $params['label'] = $this->request->get('label', $config['label'], 'trim');
        $params['text'] = $text;
        $params['label'] = $lable;

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
//        header('Content-Type: ' . $qrCode->getContentType());
//        $response->content($qrCode->writeString());

        // 写入到文件

        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';

            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath,);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $qrcodename=md5(implode('', $params)) . '.' . $config['format'];
            }
        }

//        return $response;
        return '/uploads/qrcode/'.$qrcodename;
    }
}
